Skip to content

Latest commit

 

History

History
89 lines (76 loc) · 2.39 KB

File metadata and controls

89 lines (76 loc) · 2.39 KB

334. Increasing Triplet Subsequence

Given an integer array nums, return trueif there exists a triple of indices(i, j, k)such thati < j < kandnums[i] < nums[j] < nums[k]. If no such indices exists, return false.

Example 1:

Input: nums = [1,2,3,4,5] Output: true Explanation: Any triplet where i < j < k is valid. 

Example 2:

Input: nums = [5,4,3,2,1] Output: false Explanation: No triplet exists. 

Example 3:

Input: nums = [2,1,5,0,4,6] Output: true Explanation: The triplet (3, 4, 5) is valid because nums[3] == 0 < nums[4] == 4 < nums[5] == 6. 

Constraints:

  • 1 <= nums.length <= 105
  • -231 <= nums[i] <= 231 - 1

Follow up: Could you implement a solution that runs in O(n) time complexity and O(1) space complexity?

Solutions (Ruby)

1. Solution

# @param {Integer[]} nums# @return {Boolean}defincreasing_triplet(nums)min3=[nil,nil,nil]nums.eachdo |x| ifmin3[1].nil?min3[1]=xelsifmin3[2].nil? && x <= min3[1]min3[1]=xelsifmin3[2].nil?min3[2]=xelsifx > min3[2]returntrueelsifx > min3[1]min3[2]=xelsifmin3[0].nil? && x < min3[1]min3[0]=xelsif !min3[0].nil? && x > min3[0]min3=[nil,min3[0],x]elsif !min3[0].nil? && x < min3[0]min3[0]=xendendfalseend

Solutions (Rust)

1. Solution

implSolution{pubfnincreasing_triplet(nums:Vec<i32>) -> bool{letmut min3 = (None,None,None);for x in nums {match min3 {(_,None, _) => min3.1 = Some(x),(_,Some(b),None)if x < b => min3.1 = Some(x),(_,Some(b),None)if x > b => min3.2 = Some(x),(_,Some(b),Some(c))if x > c => returntrue,(_,Some(b),Some(c))if x > b => min3.2 = Some(x),(None,Some(b),Some(c))if x < b => min3.0 = Some(x),(Some(a),Some(b),Some(c))if x > a => min3 = (None,Some(a),Some(x)),(Some(a),Some(b),Some(c))if x < a => min3.0 = Some(x), _ => (),}}false}}
close